import axios from 'axios'
import { ElMessage } from 'element-plus'

const service = axios.create({
  baseURL: '/api',
  timeout: 10000
})

service.interceptors.request.use(config => {
  const token = localStorage.getItem('crm-token')
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
}, error => Promise.reject(error))

service.interceptors.response.use(
  response => {
    if (response.data && response.data.success === false) {
      let msg = response.data.message || '操作失败';
      if (msg.match(/SQLIntegrityConstraintViolationException|foreign key constraint fails|Cannot delete or update a parent row/)) {
        msg = '删除失败：存在关联数据，无法删除！';
      }
      const error = new Error(msg);
      error.response = { data: { ...response.data, message: msg } };
      throw error;
    }
    return response.data;
  },
  error => {
    let msg = '请求失败'
    if (error.response) {
      let rawMsg = error.response.data?.message || `请求失败(${error.response.status})`;
      if (rawMsg.match(/SQLIntegrityConstraintViolationException|foreign key constraint fails|Cannot delete or update a parent row/)) {
        rawMsg = '删除失败：存在关联数据，无法删除！';
      }
      msg = rawMsg;
    }
    ElMessage.error(msg)
    return Promise.reject(error)
  }
)

export default service 